<template>
  <Modal v-model="showModal" fullscreen @on-cancel="showModal = false">
    <div class="header" slot="header">
      <span> {{ configTitle }}</span>
      <span class="search"
        ><Button
          size="small"
          icon="ios-search"
          @click="showTable = !showTable"
        ></Button
      ></span>
      <span class="title">{{ title }}</span>
    </div>
    <div class="config-con">
      <div class="config-editor" ref="configEditor"></div>
      <div class="quill-editor">
        <quill-editor
          ref="quillEditor"
          v-model="content"
          :options="editorOption"
          @change="onEditorChange($event)"
        />
      </div>
      <div class="config-list" v-show="showTable">
        <div class="header">
          <Input
            v-model="param.key"
            placeholder="请输入关键字..."
            style="width: 300px"
          />
          <Button type="primary" @click="handleSearch" style="margin: 0 1rem"
            >查询</Button
          >
          <Button @click="showAdd = !showAdd">新建</Button>
        </div>
        <div class="table-con" ref="tableCon">
          <Table
            border
            :columns="columns"
            :max-height="tableHeight"
            :data="tableData"
          ></Table>
        </div>
        <div class="page-con">
          <NrPage
            :current="param.pageIndex"
            :total="total"
            :page-size="param.pageSize"
            @on-change="handlePageChange"
            @on-page-size-change="handleSizeChange"
          >
          </NrPage>
        </div>
      </div>
    </div>
    <div class="foot-con" slot="footer">
      <Button @click="showModal = false">取消</Button>
      <Button type="primary" @click="handleSave">保存</Button>
    </div>
    <Modal
      v-model="showAdd"
      title="添加新配置"
      @on-cancel="showAdd = false"
      @on-ok="handleAdd"
    >
      <Form :model="formData" :rules="ruleValidate">
        <FormItem label="配置名称" prop="name">
          <Input v-model="formData.name" />
        </FormItem>
        <FormItem label="配置标识" prop="path">
          <Input v-model="formData.path" />
        </FormItem>
        <FormItem label="配置编码" prop="code">
          <Input v-model="formData.code" />
        </FormItem>
      </Form>
    </Modal>
    <Spin fix v-show="loading"></Spin>
  </Modal>
</template>

<script>
import jsoneditor from "jsoneditor";
import "jsoneditor/dist/jsoneditor.css";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
import store from "@/store";

import { searchConfig, saveConfig, deleteConfig, getConfig } from "@/api";
import { setGlobalData } from "../initMicroApps";
// import EventBus from "@/utils/EventBus";

export default {
  data() {
    return {
      showAdd: false,
      total: 0,
      loading: false,
      showTable: false,
      showModal: false,
      content: "<h2>I am Example</h2>",
      editorOption: {},
      configTitle: "配置管理",
      configEditor: null,
      curPath: "",
      tableHeight: 600,
      curConfig: {},
      tableData: [],
      formData: {
        name: "",
        path: "",
        config: "",
        detail: "",
      },
      ruleValidate: {
        name: [
          {
            required: true,
            message: "请输入配置名！",
            trigger: "blur",
          },
        ],
        path: [
          {
            required: true,
            message: "请输入标识！",
            trigger: "blur",
          },
        ],
      },
      param: {
        pageIndex: 1,
        pageSize: 15,
        key: "",
      },
      columns: [
        {
          title: "序号",
          type: "index",
          width: 100,
        },
        {
          title: "配置标识",
          key: "path",
        },
        {
          title: "配置名称",
          key: "name",
        },
        {
          title: "操作",
          align: "center",
          render: (h, param) => {
            return (
              <span>
                <Button
                  type="text"
                  on-click={() => {
                    this.getCurConfig(param.row.code);
                  }}
                >
                  编辑
                </Button>
                <Button
                  type="text"
                  on-click={() => {
                    this.handleDelete(param);
                  }}
                >
                  删除
                </Button>
              </span>
            );
          },
        },
      ],
    };
  },
  computed: {
    title() {
      return this.curConfig && this.curConfig.name
        ? `当前配置：${this.curConfig.name}`
        : "";
    },
  },
  components: {
    quillEditor,
  },
  watch: {
    $route() {
      this.getCurConfig();
    },
  },
  mounted() {
    this.handleSearch();
    this.getCurConfig();
    // EventBus.$on("set-cur-config", this.handleSetConfig);
  },

  beforeDestroy() {
    // EventBus.$off("set-cur-config", this.handleSetConfig);
  },

  methods: {
    handleSetConfig(config) {
      this.curConfig = config;
      if (!this.configEditor) {
        const options = {
          mode: "code",
          modes: ["code", "text", "tree", "preview"],
        };
        this.configEditor = new jsoneditor(this.$refs.configEditor, options);
      }
      this.content =
        this.curConfig && this.curConfig.detail ? this.curConfig.detail : "";
      this.configEditor.set(
        this.curConfig && this.curConfig.config
          ? JSON.parse(this.curConfig.config)
          : {}
      );
    },
    randomString(len) {
      len = len || 32;
      let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = $chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },

    handlePageChange(page) {
      this.param.pageIndex = page;
      this.handleSearch();
    },

    handleSizeChange(size) {
      this.param.pageSize = size;
      this.handleSearch();
    },

    async handleDelete(param) {
      this.loading = true;
      await deleteConfig(param.row.id);
      this.handleSearch();
      this.loading = false;
    },

    async handleSearch() {
      this.loading = true;
      let res = await searchConfig({
        ...this.param,
        pageIndex: this.param.pageIndex - 1,
      });
      this.tableData = res.rows;
      this.total = res.totalElements;
      this.loading = false;
    },

    async handleAdd() {
      if (!this.formData.code) {
        this.formData.code = this.randomString();
      }
      await saveConfig(this.formData);
      await this.handleSearch();
      this.formData = {
        name: "",
        path: "",

        config: "",
        detail: "",
      };
    },

    async getCurConfig(path) {
      this.curPath = path ? path : this.$route.name;
      let config = {};
      try {
        config = await getConfig("path", this.curPath);
        if (!config) {
          config = {};
        }
      } catch {
        config = {};
      }
      this.handleSetConfig(config);
      if (this.$route.meta.name == this.curPath) {
        if (this.curConfig.config) {
          let config = JSON.parse(this.curConfig.config);
          store.commit("SET_CURCONFIG", config);
        } else {
          store.commit("SET_CURCONFIG", {});
        }
        setGlobalData(null, null, this.curConfig);
      }
      this.showTable = false;
    },

    handleCancel() {
      this.$emit("hide-config");
    },

    onEditorChange({ html }) {
      this.content = html;
    },

    handleShowModal() {
      this.showModal = !this.showModal;
      if (!this.showModal) {
        return;
      }
      this.curPath = this.$route.meta.code;
    },

    async handleSave() {
      this.loading = true;
      let config = this.configEditor.get();
      let param = {
        id: this.curConfig.id ? this.curConfig.id : "",
        name:
          this.curConfig && this.curConfig.name
            ? this.curConfig.name
            : this.$route.name,
        path:
          this.curConfig && this.curConfig.path
            ? this.curConfig.path
            : this.$route.name,
        config: JSON.stringify(config),
        detail: this.content,
      };
      debugger
      await saveConfig(param);
      this.curConfig = param;
      if (this.$route.meta.code == this.curPath) {
        store.commit("SET_CURCONFIG", config);
        setGlobalData(null, null, this.curConfig);
      }
      this.loading = false;
    },
  },
};                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
</script>

<style lang="scss" scoped>
.config-con {
  width: 100%;
  height: 100%;
  display: flex;
  overflow: hidden;
  .config-editor {
    width: 50%;
    height: 100%;
  }
  .quill-editor {
    flex: 1;
    padding-left: 0.5rem;
    height: 100%;
  }
  .config-list {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: white;
    padding: 0 1rem;
    z-index: 10;
    .header {
      width: 100%;
      height: 3rem;
      line-height: 3rem;
      position: relative;
    }
    .table-con {
      width: 100%;
      height: calc(100% - 6.5rem);
    }
    .page-con {
      line-height: 3rem;
      height: 3rem;
      text-align: right;
    }
  }
}
.header {
  font-size: 1rem;
  .title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
  .search {
    margin-left: 1rem;
    cursor: pointer;
  }
}

::v-deep {
  .ql-container {
    height: calc(100% - 3.5rem);
  }
  .jsoneditor-menu > button.jsoneditor-expand-all {
    background-position: 0 1.2rem;
  }
  .jsoneditor-menu > button.jsoneditor-collapse-all {
    background-position: 0.1rem -4.5rem;
  }
  div.jsoneditor-tree button.jsoneditor-expanded {
    background-position: 0 -3.4rem;
  }
  div.jsoneditor-tree button.jsoneditor-collapsed {
    background-position: 0 -2.2rem;
  }
  div.jsoneditor-tree button.jsoneditor-contextmenu-button {
    background-position: -2.2rem -3.3rem;
  }
  div.jsoneditor-tree button.jsoneditor-dragarea {
    background-position: -3.2rem -3.3rem;
  }
  .jsoneditor-menu > button.jsoneditor-transform {
    background-position: -6.8rem -4.5rem;
  }
  .jsoneditor-menu > button.jsoneditor-sort {
    background-position: -5.5rem -4.5rem;
  }
  .jsoneditor-menu > button.jsoneditor-undo {
    background-position: -1rem -4.5rem;
  }
  .jsoneditor-menu > button.jsoneditor-redo {
    background-position: -2.2rem -4.5rem;
  }
  .jsoneditor-menu > button.jsoneditor-format {
    background-position: -3.5rem -5.7rem;
  }
  .jsoneditor-menu > button.jsoneditor-compact {
    background-position: -3.3rem -4.5rem;
  }
  .jsoneditor-menu > button.jsoneditor-repair {
    background-position: -4.5rem -4.5rem;
  }
  .jsoneditor-search button.jsoneditor-refresh {
    background-position: -4.6rem -3.3rem;
  }
  .jsoneditor-search button.jsoneditor-next {
    background-position: -5.9rem -2.2rem;
  }
  .jsoneditor-search button.jsoneditor-next:hover {
    background-position: -5.9rem -2.2rem;
  }
  .jsoneditor-search button.jsoneditor-previous {
    background-position: -6.9rem -3.3rem;
  }
}
</style>
